package com.hzbank.game.mini.service.impl;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.hzbank.game.mini.model.ReturnT;
import com.hzbank.game.mini.service.BackgroundService;

import net.sf.json.JSONObject;

@Service
public class BackgroundServiceImpl implements BackgroundService{

	@Resource
	RestTemplate restTemplate;
	
	@Override
	public ReturnT<String> mergeIMG(File file) {
		try {
            BufferedImage big = ImageIO.read(new File("D:\\Images\\background.png"));
            //BufferedImage small = ImageIO.read(new File("D:\\Images\\2.png"));
            BufferedImage small = ImageIO.read(file);
            Graphics2D g = big.createGraphics();
            int x = (int)System.currentTimeMillis()%(big.getWidth()-small.getWidth());
            int y = (int)System.currentTimeMillis()%(big.getHeight()-small.getHeight()); 
            g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
            g.dispose();
            ImageIO.write(big, "png", new File("D:\\Images\\background.png"));
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnT<>(ReturnT.FAIL_CODE, "文件合并错误", e.getMessage());
        }
    	return ReturnT.SUCCESS;
	}

	@Override
	public ReturnT<String> dealCode(String code) {
        //向微信服务器 使用登录凭证 code 获取 session_key 和 openid
		
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + "wx3208b20e7e2b26b4" +
                "&secret=" + "e20b8cf9ef35c59f72ffab5e3c38b89a" +
                "&js_code=" + code +
                "&grant_type=authorization_code";
 
        ResponseEntity<String> res = restTemplate.getForEntity(url, String.class);
        JSONObject jsonObject = JSONObject.fromObject(res.getBody());
        System.out.println("jsonObject============="+jsonObject);
        
        System.out.println(jsonObject.get("openid").toString());
        ReturnT<String> result = new ReturnT<String>(jsonObject.get("openid").toString());
        return result;
	}

}
